package com.ruoyi.web.service;

import org.apache.http.client.methods.CloseableHttpResponse; // 引入HTTP响应类
import org.apache.http.client.methods.HttpGet; // 引入HTTP GET请求类
import org.apache.http.impl.client.CloseableHttpClient; // 引入可关闭的HTTP客户端类
import org.apache.http.impl.client.HttpClients; // 引入HTTP客户端构建类
import org.apache.http.util.EntityUtils; // 引入实体工具类
import com.fasterxml.jackson.databind.JsonNode; // 引入JSON节点类
import com.fasterxml.jackson.databind.ObjectMapper; // 引入对象映射类
/*
 *  @author 雨安
 *  类名： WeChatOpenIdService
 *  创建时间：2025/2/18
 */
public class WeChatOpenIdService {
    private String appId; // 微信公众号的App ID
    private String appSecret; // 微信公众号的App Secret
    // 构造函数，初始化App ID和App Secret
    public WeChatOpenIdService(String appId, String appSecret) {
        this.appId = appId; // 设置App ID
        this.appSecret = appSecret; // 设置App Secret
    }
    // 通过code获取openid
    public String getOpenId(String code) throws Exception {
        // 构建请求URL
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId +
                "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";
        // 创建HTTP客户端
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建GET请求
        HttpGet httpGet = new HttpGet(url);
        // 执行请求并获取响应
        CloseableHttpResponse response = httpClient.execute(httpGet);
        try {
            // 解析响应内容
            String jsonResponse = EntityUtils.toString(response.getEntity(), "UTF-8");
            // 使用Jackson库解析JSON
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(jsonResponse);
            // 获取openid
            String openId = jsonNode.get("openid").asText();
            // 返回openid
            return openId;
        } finally {
            response.close(); // 关闭响应
        }
    }
}
